<?php
use Model\User\User;
use Core\Response;
use Core\Request;
use Core\View;

class _login
{
    public $defaultFrom = '/';
	public $userinfo = [];

	public function initc()
	{
		$userinfo = $this->isLogin();
		if ($userinfo) {
			$this->userinfo = $userinfo;
		}
	}

	//是否登录
	public function isLogin()
	{
		$rs = User::getUserCookie();
		return !empty($rs) ? $rs : FALSE;
	}

	//是否登录, 接口
	public function iisLogin()
    {
        $rs = User::getUserCookie();
        if (!empty($rs)) {
            User::setUserCookie($rs, $rs['expire']);
            $rs = ['unid' => $rs['unid']];
        }
        Response::success($rs);
    }

	//登录
	public function index()
	{
		$from = Request::Cookie('REF_URI', '');
		if (empty($from)) {
	        $from = $this->defaultFrom;
        } else {
            $from = urldecode($from);
        }

		if (Request::isPost()) {
			//todo 防止重复提交
			$mobile = Request::Post('mobile');
			$username = Request::Post('username');
			$password = Request::Post('password');
			$remember_me  = Request::Post('remember_me');
			$expire = $remember_me ? 86400*7 : 0;

			$user = User::verifyUserLogin($username, $password);
			if ($user) {
				//写入cookie
				User::setUserCookie($user, $expire);

				//登录成功
                User::afterLogin($user['unid']);
                Response::success(['from' => $from], '登陆成功'); //$from用于跳转
			} else {
                Response::error('用户名或密码错误, 请重新登录');
			}
		} else {
            View::$arrTplVar['from'] = $from;
            View::$arrTplVar['reg_url'] = '/user_register';
			View::display('login');
		}
	}
}
